package com.bjbn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjbn.bean.entity.FltInfoDynamic;
import com.bjbn.mapper.primary.FltInfoDynamicMapper;
import com.bjbn.service.FltInfoDynamicService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
public class FltInfoDynamicServiceImpl implements FltInfoDynamicService {

    @Autowired
    FltInfoDynamicMapper fltInfoDynamicMapper;

    @Override
    @Transactional(transactionManager = "primaryTransactionManager")
    public void saveOrUpdateFltInfoDynamic(FltInfoDynamic fltInfoDynamic) {
        fltInfoDynamic.setUPDATE_TIME(new Date());

        int retryCount = 0;
        final int maxRetry = 3;

        while (retryCount < maxRetry) {
            try {
                QueryWrapper<FltInfoDynamic> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("FLID", fltInfoDynamic.getFLID());
                val exists = fltInfoDynamicMapper.selectOne(queryWrapper);

                if (exists != null) {
                    fltInfoDynamicMapper.updateById(fltInfoDynamic);
                } else {
                    fltInfoDynamic.setBN_CREATE_TIME(new Date());
                    fltInfoDynamicMapper.insert(fltInfoDynamic);
                }
                break;
            } catch (DuplicateKeyException e) {
                retryCount++;
                if (retryCount >= maxRetry) {
                    throw e;
                }
                // 等待一小段时间后重试
                try {
                    Thread.sleep(100 * retryCount);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Interrupted during retry", ie);
                }
            }
        }
    }
}
